from django.core.validators import MinValueValidator
from django.db import models
import time


# 单位表
class FaKuyouUnit(models.Model):
    TYPE_CHOICES = [
        ('1', '单一单位'),
        ('2', '多单位')
    ]
    IS_MAIN_CHOICES = [
        ('0', '否'),
        ('1', '是')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )
    name = models.CharField(
        max_length=100,
        null=True,
        verbose_name='单位名称',
        help_text='如：千克、箱、包等'
    )
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='1',
        verbose_name='单位类型'
    )
    is_main = models.CharField(
        max_length=1,
        choices=IS_MAIN_CHOICES,
        default='0',
        verbose_name='是否主单位'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_unit'
        verbose_name = '计量单位'
        verbose_name_plural = '计量单位管理'
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['type']),
            models.Index(fields=['is_main']),
        ]
        ordering = ['name']

    def __str__(self):
        return f"{self.name}({'主单位' if self.is_main == '1' else '辅单位'})"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 如果是主单位，确保同类型下只有一个主单位
        if self.is_main == '1' and self.type == '2':
            FaKuyouUnit.objects.filter(
                type='2',
                is_main='1'
            ).exclude(pk=self.pk).update(is_main='0')

        super().save(*args, **kwargs)


# 多单位表
class FaKuyouUnitConversion(models.Model):
    """计量单位换算表"""
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    unit_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='单位组名称')

    main_unit = models.IntegerField(
        default=0,
        verbose_name='主计量单位ID',
        help_text='关联计量单位表的主键ID'
    )

    vice_unit = models.IntegerField(
        default=0,
        verbose_name='副计量单位ID',
        help_text='关联计量单位表的主键ID'
    )

    advance_rate = models.DecimalField(
        max_digits=11,
        decimal_places=2,
        default=0.00,
        verbose_name='换算进率',
        help_text='1个主单位 = 进率个副单位'
    )

    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_unit_conversion'
        verbose_name = '计量单位换算'
        verbose_name_plural = '计量单位换算'
        unique_together = [['main_unit', 'vice_unit']]  # 防止重复换算关系
        indexes = [
            models.Index(fields=['main_unit'], name='idx_main_unit'),
            models.Index(fields=['vice_unit'], name='idx_vice_unit'),
        ]

    def __str__(self):
        return f"{self.unit_name or '未命名'} (主:{self.main_unit} 副:{self.vice_unit})"

    def save(self, *args, **kwargs):
        # 自动设置时间戳
        self.createtime = int(time.time())
        self.updatetime = int(time.time())

        # 自动生成单位组名称
        if not self.unit_name:
            try:
                main = FaKuyouUnit.objects.get(pk=self.main_unit).unit_name
                vice = FaKuyouUnit.objects.get(pk=self.vice_unit).unit_name
                self.unit_name = f"{main}/{vice}"
            except Exception:
                pass

        super().save(*args, **kwargs)


# 委外工厂表
class FaKuyouFactory(models.Model):
    STATUS_CHOICES = [
        ('0', '禁用'),
        ('1', '启用')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 工厂基本信息
    customer_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='工厂编号'
    )
    customertype_id = models.IntegerField(
        default=0,
        verbose_name='客户类型ID'
    )
    customerlevel_id = models.IntegerField(
        default=1,
        verbose_name='客户等级ID'
    )
    customer_name = models.CharField(
        max_length=150,
        default='',
        verbose_name='工厂名称'
    )

    # 联系信息
    saler = models.CharField(
        max_length=100,
        default='',
        verbose_name='销售人员'
    )
    connet_name = models.CharField(
        max_length=50,
        default='',
        verbose_name='联系人'
    )
    customer_mobile = models.CharField(
        max_length=11,
        default='',
        verbose_name='手机号码'
    )
    customer_phone = models.CharField(
        max_length=20,
        default='',
        verbose_name='联系电话'
    )
    qq_wx_email = models.CharField(
        max_length=100,
        default='',
        verbose_name='QQ/微信/Email'
    )

    # 财务信息
    need_receive_account = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='应收款余额'
    )
    receive_account = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='期初应收款'
    )
    opening_prepayment = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='期初预收款'
    )
    identification = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        verbose_name='纳税人识别号'
    )
    deposit_bank = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='开户银行'
    )
    bank_number = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='银行账号'
    )

    # 其他信息
    getgoods_address = models.CharField(
        max_length=255,
        default='',
        verbose_name='收货地址'
    )
    note = models.CharField(
        max_length=255,
        default='',
        verbose_name='备注'
    )
    staff_member_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='销售人员ID'
    )
    account_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='余额日期'
    )
    third_id = models.IntegerField(
        default=0,
        verbose_name='三方系统ID'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='状态'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_factory'
        verbose_name = '委外工厂'
        verbose_name_plural = '委外工厂管理'
        indexes = [
            models.Index(fields=['customer_code']),
            models.Index(fields=['customer_name']),
            models.Index(fields=['customer_mobile']),
            models.Index(fields=['status']),
        ]
        ordering = ['customer_name']

    def __str__(self):
        return f"{self.customer_name}({self.customer_code or '无编号'})"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())

        self.createtime = now
        self.updatetime = now

        # 自动计算应收款余额
        if self.receive_account is not None and self.opening_prepayment is not None:
            self.need_receive_account = self.receive_account - self.opening_prepayment

        super().save(*args, **kwargs)


# 供应商表
class FaKuyouSuppliers(models.Model):
    STATUS_CHOICES = [
        ('0', '禁用'),
        ('1', '正常')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 供应商基础信息
    supplyer_code = models.CharField(
        max_length=30,
        default='',
        verbose_name='供应商编号'
    )
    supplyertype_id = models.IntegerField(
        default=0,
        verbose_name='供应商类别ID'
    )
    supplyer_name = models.CharField(
        max_length=120,
        verbose_name='供应商名称'
    )

    # 联系信息
    first_connect_name = models.CharField(
        max_length=100,
        default='',
        verbose_name='联系人'
    )
    first_connect_mobile = models.CharField(
        max_length=11,
        verbose_name='手机号码'
    )
    first_connect_phone = models.CharField(
        max_length=20,
        default='',
        blank=True,
        verbose_name='联系电话'
    )
    qq_wx_email = models.CharField(
        max_length=120,
        default='',
        blank=True,
        verbose_name='QQ/微信/Email'
    )
    connect_address = models.CharField(
        max_length=255,
        default='',
        blank=True,
        verbose_name='联系地址'
    )

    # 财务信息
    need_give_account = models.DecimalField(
        max_digits=11,
        decimal_places=2,
        default=0.00,
        validators=[MinValueValidator(0)],
        verbose_name='应付款余额'
    )
    receive_account = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='期初应付款'
    )
    opening_payable = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        verbose_name='期初应付款'
    )
    opening_prepayment = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        verbose_name='期初预付款'
    )
    vat_rate = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='增值税税率(%)'
    )

    # 银行信息
    identification = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='纳税人识别号'
    )
    deposit_bank = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        verbose_name='开户银行'
    )
    bank_number = models.CharField(
        max_length=30,
        null=True,
        blank=True,
        verbose_name='银行账号'
    )

    # 时间信息
    account_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='余额日期'
    )

    # 状态控制
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='1',
        verbose_name='状态'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_suppliers'
        verbose_name = '供应商'
        verbose_name_plural = '供应商管理'
        indexes = [
            models.Index(fields=['supplyer_code']),
            models.Index(fields=['supplyer_name']),
            models.Index(fields=['first_connect_mobile']),
            models.Index(fields=['status']),
        ]
        ordering = ['supplyer_name']

    def __str__(self):
        return f"{self.supplyer_name}({self.supplyer_code})"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        super().save(*args, **kwargs)


# 客户表
class FaKuyouCustomer(models.Model):
    STATUS_CHOICES = [
        ('0', 'Inactive'),
        ('1', 'Active'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    customer_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='客户编号')
    customertype_id = models.SmallIntegerField(default=0, verbose_name='客户类别')
    customerlevel_id = models.SmallIntegerField(default=1, verbose_name='客户等级')
    customer_name = models.CharField(max_length=150, default='', verbose_name='客户名称')
    saler = models.CharField(max_length=100, default='', verbose_name='销售人员')
    connet_name = models.CharField(max_length=50, default='', verbose_name='联系人')
    customer_mobile = models.CharField(max_length=11, default='', verbose_name='客户手机')
    customer_phone = models.CharField(max_length=20, default='', verbose_name='客户座机')
    qq_wx_email = models.CharField(max_length=100, default='', verbose_name='QQ/微信/Email')
    need_receive_account = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                               verbose_name='应收款余额')
    receive_account = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                          verbose_name='期初应收款')
    opening_prepayment = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True,
                                             verbose_name='期初预收款')
    identification = models.CharField(max_length=100, null=True, blank=True, verbose_name='纳税人识别号')
    getgoods_address = models.CharField(max_length=255, default='', verbose_name='收货地址')
    note = models.CharField(max_length=255, default='', verbose_name='备注')
    deposit_bank = models.CharField(max_length=255, null=True, blank=True, verbose_name='开户银行')
    bank_number = models.CharField(max_length=255, null=True, blank=True, verbose_name='银行卡号')
    staff_member_id = models.IntegerField(null=True, blank=True, verbose_name='销售人员')
    account_time = models.PositiveIntegerField(null=True, blank=True, verbose_name='余额日期')
    third_id = models.IntegerField(default=0, null=True, blank=True, verbose_name='三方ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1', verbose_name='状态')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_customers'
        verbose_name = '客户表'
        verbose_name_plural = '客户表'

    def __str__(self):
        return self.customer_name


# 客户等级表
class FaKuyouCustomerLevel(models.Model):
    """客户等级表"""
    STATUS_CHOICES = (
        ('0', '禁用'),
        ('1', '正常'),
    )

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID',
        help_text='创建该等级的管理员ID'
    )
    name = models.CharField(
        max_length=100,
        default='',
        verbose_name='等级名称',
        help_text='客户等级名称（如VIP1、普通客户等）'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='状态',
        help_text='控制等级是否可用'
    )

    class Meta:
        db_table = 'fa_kuyou_customerlevel'
        verbose_name = '客户等级'
        verbose_name_plural = '客户等级'
        indexes = [
            models.Index(fields=['status'], name='customer_level_status_idx'),
        ]

    def __str__(self):
        return f"{self.name} ({self.get_status_display()})"


# 客户分类表
class FaKuyouCustomerType(models.Model):
    """客户分类表（支持无限级分类）"""
    STATUS_CHOICES = (
        ('0', '禁用'),
        ('1', '正常'),
    )

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID',
        help_text='创建该分类的管理员ID'
    )
    type_name = models.CharField(
        max_length=100,
        verbose_name='分类名称',
        help_text='客户分类名称'
    )
    pid = models.IntegerField(
        default=0,
        verbose_name='父级ID',
        help_text='0表示一级分类'
    )
    path = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='路径',
        help_text='格式如: 0,1,2 表示三级分类'
    )
    type_image = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='分类图片',
        help_text='分类图标URL'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='0',
        verbose_name='状态',
        help_text='控制分类是否可用'
    )

    class Meta:
        db_table = 'fa_kuyou_customertype'
        verbose_name = '客户分类'
        verbose_name_plural = '客户分类'
        indexes = [
            models.Index(fields=['pid'], name='customer_type_pid_idx'),
            models.Index(fields=['status'], name='customer_type_status_idx'),
        ]

    def __str__(self):
        return f"{self.type_name} (ID:{self.id})"

    def save(self, *args, **kwargs):
        """自动处理路径"""
        # 首次保存时设置path
        if not self.pk:
            super().save(*args, **kwargs)  # 必须先保存获取ID

        # 设置path路径
        if self.pid == 0:
            self.path = '0'
        else:
            try:
                parent = FaKuyouCustomerType.objects.get(pk=self.pid)
                self.path = f"{parent.path},{self.pid}"
            except FaKuyouCustomerType.DoesNotExist:
                self.pid = 0
                self.path = '0'

        super().save(*args, **kwargs)

    def get_children(self):
        """获取直接子分类"""
        return FaKuyouCustomerType.objects.filter(pid=self.id, status='1')

    def get_all_children(self):
        """获取所有子分类（递归）"""
        children = []
        for child in self.get_children():
            children.append(child)
            children.extend(child.get_all_children())
        return children

    @property
    def level(self):
        """获取分类层级"""
        if not self.path:
            return 1
        return len(self.path.split(','))

    @classmethod
    def get_tree_data(cls, root_id=0):
        """获取树形结构数据"""
        root = cls.objects.get(pk=root_id) if root_id != 0 else None
        tree = []

        def build_node(node):
            children = node.get_children()
            return {
                'id': node.id,
                'name': node.type_name,
                'image': node.type_image,
                'status': node.status,
                'level': node.level,
                'children': [build_node(child) for child in children]
            }

        if root:
            tree.append(build_node(root))
        else:
            for top_node in cls.objects.filter(pid=0).order_by('id'):
                tree.append(build_node(top_node))

        return tree

    @classmethod
    def get_leaf_categories(cls, include_disabled=False):
        """
        获取所有叶子节点分类（没有子分类的分类）
        :param include_disabled: 是否包含禁用的分类
        :return: 叶子节点分类查询集
        """
        # 获取所有有父分类的ID（即非顶级分类）
        subquery = cls.objects.filter(pid__gt=0).values_list('pid', flat=True).distinct()

        # 查询条件：不在父分类ID列表中（即没有子分类）的分类
        queryset = cls.objects.exclude(id__in=subquery)

        if not include_disabled:
            queryset = queryset.filter(status='1')

        return queryset.order_by('type_name')

    @classmethod
    def get_leaf_categories_by_level(cls, level, include_disabled=False):
        """
        获取指定层级的叶子节点分类
        :param level: 要查询的层级（从1开始）
        :param include_disabled: 是否包含禁用的分类
        :return: 指定层级的叶子节点分类查询集
        """
        # 计算路径应有的长度
        path_length = level

        # 获取所有分类的path长度等于指定层级的分类
        queryset = cls.objects.annotate(
            path_length=models.functions.Length('path') - models.functions.Length(
                models.functions.Replace('path', ',', '')
            ) + 1
        ).filter(path_length=path_length)

        # 排除有子分类的节点
        subquery = cls.objects.filter(pid__gt=0).values_list('pid', flat=True).distinct()
        queryset = queryset.exclude(id__in=subquery)

        if not include_disabled:
            queryset = queryset.filter(status='1')

        return queryset.order_by('type_name')


# 单号配置表
class FaKuyouPrefix(models.Model):
    """单据编号前缀配置表"""
    # 枚举选项
    YES_NO_CHOICES = [
        ('1', '包含'),
        ('2', '不包含'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    type = models.PositiveSmallIntegerField(
        default=1,
        unique=True,
        verbose_name='单据类型'
    )
    name = models.CharField(
        max_length=255,
        default='',
        verbose_name='单据名称'
    )
    prefix = models.CharField(
        max_length=10,
        default='',
        unique=True,
        verbose_name='前缀'
    )
    year = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='年'
    )
    month = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='月'
    )
    day = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='日'
    )
    hour = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='时'
    )
    minute = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='分'
    )
    second = models.CharField(
        max_length=1,
        choices=YES_NO_CHOICES,
        default='1',
        verbose_name='秒'
    )
    start = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='起始编号'
    )
    strlen = models.PositiveIntegerField(
        default=0,
        null=True,
        blank=True,
        verbose_name='数字长度'
    )
    example = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='示例'
    )
    dbname = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='关联表名'
    )
    field = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='关联字段'
    )

    class Meta:
        db_table = 'fa_kuyou_prefix'
        verbose_name = '单据编号设置'
        verbose_name_plural = '单据编号设置'
        ordering = ['type']

    def __str__(self):
        return f"{self.name}({self.prefix})"


# 支出类别
class FaKuyouExpendType(models.Model):
    STATUS_CHOICES = (
        ('0', '禁用'),
        ('1', '正常'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    name = models.CharField(max_length=120, default='', verbose_name='名称')
    image = models.CharField(max_length=255, default='', verbose_name='图片')
    pid = models.IntegerField(default=0, verbose_name='上级分类ID')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1', verbose_name='状态')
    path = models.CharField(max_length=255, null=True, blank=True)
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')

    class Meta:
        db_table = 'fa_kuyou_expend_type'
        verbose_name = '支出类别表'
        verbose_name_plural = verbose_name

    def save(self, *args, **kwargs):
        now = int(time.time())
        if not self.createtime:
            self.createtime = now
        self.updatetime = now
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name


# 账户表
class FaKuyouAccounts(models.Model):
    ACCOUNT_TYPE_CHOICES = (
        ('1', '现金'),
        ('2', '银行存款'),
    )
    IS_DEFAULT_CHOICES = (
        ('0', '否'),
        ('1', '是'),
    )
    STATUS_CHOICES = (
        ('0', '关闭'),
        ('1', '正常'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    account_coding = models.CharField(max_length=100, verbose_name='账户编号')
    account_name = models.CharField(max_length=100, verbose_name='账户名称')
    balance = models.DecimalField(max_digits=15, decimal_places=4, null=True, blank=True, verbose_name='当前余额')
    start_account_balance = models.DecimalField(max_digits=15, decimal_places=4, default=0.0000,
                                                verbose_name='期初余额')
    start_account_time = models.CharField(max_length=20, default='', verbose_name='建账日期')
    account_type_id = models.CharField(max_length=1, choices=ACCOUNT_TYPE_CHOICES, default='1', verbose_name='账户类型')
    is_default = models.CharField(max_length=1, choices=IS_DEFAULT_CHOICES, default='0', null=True, blank=True,
                                  verbose_name='是否默认')
    status = models.CharField(max_length=1, choices=STATUS_CHOICES, default='1', null=True, blank=True,
                              verbose_name='状态')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')
    deletetime = models.IntegerField(null=True, blank=True, verbose_name='删除时间')

    class Meta:
        db_table = 'fa_kuyou_accounts'
        verbose_name = '账户表'
        verbose_name_plural = verbose_name

    def save(self, *args, **kwargs):
        now = int(time.time())
        if not self.createtime:
            self.createtime = now
        self.updatetime = now
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.account_name} ({self.account_coding})"


# 应收账款明细表
class FaKuyouAccountsReceivable(models.Model):
    BUSINESS_TYPE_CHOICES = (
        ('0', '期初余额'),
        ('1', '预收冲应收'),
        ('2', '预付冲应付'),
        ('3', '应收冲应付'),
        ('4', '应收转应收'),
        ('5', '应付转应付'),
        ('6', '普通销售'),
        ('7', '销售退回'),
        ('8', '其他收入'),
        ('9', '收款'),
        ('10', '核销'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    customers_id = models.IntegerField(default=0)
    purchase_time = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=100, default='')
    business_type = models.CharField(
        max_length=2,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True
    )
    receivable = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    advance = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    staff_member_id = models.IntegerField(null=True, blank=True)
    remark = models.CharField(max_length=255, null=True, blank=True)
    sale_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    receivable_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    amount = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    cost = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    real_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    createtime = models.IntegerField(null=True, blank=True)
    updatetime = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'fa_kuyou_accounts_receivable'
        verbose_name = '应收账款明细表'
        verbose_name_plural = verbose_name

    def get_type(self, type_index):
        for index, name in self.BUSINESS_TYPE_CHOICES:
            if index == type_index:
                return name
        return ''

    def __str__(self):
        return f"{self.purchase_code} (Customer: {self.customers_id}, Amount: {self.receivable_money})"


# 应付账款明细表
class FaKuyouAccountsCopeWith(models.Model):
    BUSINESS_TYPE_CHOICES = (
        ('0', '期初余额'),
        ('1', '预收冲应收'),
        ('2', '预付冲应付'),
        ('3', '应收冲应付'),
        ('4', '应收转应收'),
        ('5', '应付转应付'),
        ('6', '普通采购'),
        ('7', '采购退回'),
        ('8', '其他支出'),
        ('9', '付款'),
        ('10', '核销'),
    )

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    suppliers_id = models.IntegerField(default=0)
    purchase_time = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=100, default='')
    business_type = models.CharField(
        max_length=2,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True
    )
    receivable = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True
    )
    advance = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True
    )
    remark = models.CharField(max_length=255, null=True, blank=True)
    sale_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    receivable_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    amount = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    cost = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    real_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True
    )
    createtime = models.IntegerField(null=True, blank=True)
    updatetime = models.IntegerField(null=True, blank=True)

    class Meta:
        db_table = 'fa_kuyou_accounts_copewith'
        verbose_name = '应付账款明细表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.purchase_code} (Supplier: {self.suppliers_id}, Amount: {self.receivable_money})"
